<template>
  <div class="content">
    <jc-button
      :btn-arr="['reload', 'sub', 'remove', 'option', 'closure', 'closeHang', 'hangUp', 'hangUp1', 'pass', 'push', 'batchFill', !list.length && 'check', 'config', 'matLi']"
      :disab-arr="['close', 'cancel', 'using', 'freeze']"
      :fbillno="fbillno"
      url="tPrdMo/queryMoList"
      config="T_PRD_MO"
      @refresh="handleGetUntreated"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @del="delPublic"
      @handleCom1="handleCom1(1)"
      @handleCom2="handleCom1(2)"
      @toExcel="handleExport"
      @pushDown="pushDown"
      @check="check('up')"
      @check1="check('down')"
      @closure="closure(1)"
      @closure1="closure(2)"
      @closeHang="closeHang(1)"
      @closeHang1="closeHang(2)"
      @hangUp="hangUp(1)"
      @hangUp1="hangUp(2)"
      @hangUp2="entryHangUp(1)"
      @hangUp3="entryHangUp(2)"
      @matLi="isMaterialsDialog=true"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div ref="tableCon" class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="detailPurchase"
      >
        <!--订单编码-->
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="detailPurchase(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--审核状态-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentStatus }}</el-tag>
        </template>
        <!--领料状态-->
        <template v-slot:btnStates="col">
          <span v-if="col.scope.row.stateColor === ''" />
          <el-tag v-else :type="col.scope.row.pickColor">{{ col.scope.row.fpickstatus }}</el-tag>
        </template>
        <!--挂起状态-->
        <template v-slot:text4Slot="col">
          <el-tag v-if="col.scope.row.fispending === 1" type="danger">{{ $t('btn.hangUp') }}</el-tag>
          <el-tag v-else>{{ $t('btn.hangUp2') }}</el-tag>
        </template>
        <!--明细挂起状态-->
        <template v-slot:text2Slot="col">
          <el-tag v-if="col.scope.row.zfispending === 1" type="danger">{{ $t('btn.hangUp') }}</el-tag>
          <el-tag v-else>{{ $t('btn.hangUp2') }}</el-tag>
        </template>
        <!--齐套-->
        <template v-slot:text3Slot="col">
          <el-tag v-if="col.scope.row.fulls === '不齐套'" type="danger">{{ $t('market.fulls2') }}</el-tag>
          <el-tag v-else>{{ $t('market.fulls') }}</el-tag>
        </template>
        <!--结案-->
        <template v-slot:text5Slot="col">
          <el-tag v-if="col.scope.row.fendstatus === 'B'" type="danger">{{ $t('btn.settle') }}</el-tag>
          <el-tag v-else-if="col.scope.row.fendstatus === 'C'" type="warning">{{ $t('market.closure1') }}</el-tag>
          <el-tag v-else>{{ $t('market.normal') }}</el-tag>
        </template>
      </jc-table>
      <cardTab @search="handleQueryBomList" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <!--下推-->
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX" @change="handleOrder">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div v-if="orderBool" style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
            :disabled="item.fid===185||item.fid===186"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 用料清单查询 -->
    <el-dialog
      v-dialogDrag
      :title="$t('menu.proIngredient')"
      model
      :visible.sync="isMaterialsDialog"
      :close-on-click-modal="false"
      width="80%"
      top="0"
      append-to-body
    >
      <productionEdit :msg="ppbombillno" />
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  queryMoList,
  unauditPrdMos,
  auditPrdMos,
  unsubmitPrdMos,
  submitPrdMos,
  delPrdMos,
  pushToPrdInstock,
  pushToPrdUninstock,
  pushMoCheck,
  insertProcess,
  insertOutsource,
  pushProToPicking,
  pushProToReturnMater,
  pushProToSupplement,
  updatefispending, updateDetailedfispending, endOrder, unEnd, entryEnd, entryUnEnd
} from '@/api/production/productionList'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina, toPickStues } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  name: 'ProOrderList',
  components: {
    cardTab: () => import('@/components/cardTab'),
    upDown: () => import('@/components/upDown'),
    search,
    filtration,
    jcButton,
    productionEdit: () => import('@/views/production/collect/productionEdit')
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    },
    searchData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fentryData: [],
      ppbombillno: '',
      isMaterialsDialog: false,
      ftype: 23,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      // '生产入库单' 生产退库单 品质检验单'生产流程单''外包工序单', 生产领料 退料 补料大
      orderLX: this.$t('menu.proStirageOrder'),
      receipts: [this.$t('menu.proStirageOrder'), this.$t('menu.proTuiStockDetail'), this.$t('menu.qualityOrder'),
        this.$t('menu.workFlowOrder'), this.$t('menu.outProcessOrder'), this.$t('menu.proPickLian'),
        this.$t('menu.proSupplTong'), this.$t('menu.supplementary')], // 生产
      fbillTypeId: 184,
      convert: this.$t('market.scbjy'),
      billTypeData: [], // 采购订单单据
      isdanjuDialog: false,
      // 表头
      tableData: [], // 销售数据
      tableHeight: '70vh',
      fbillno: '',
      tableHeader: [
        { label: this.$t('market.proOrderNo'), type: 'tag', prop: 'fbillNo', width: '120' },
        // { label: this.$t('market.billType'), prop: 'fbillType' },
        { label: this.$t('market.fdate'), prop: 'fdate', width: '90' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentStatus', width: '100' },
        { label: this.$t('market.paezText1'), prop: 'fpaezText' },
        { label: this.$t('market.productmodel'), prop: 'fproductmodel', width: '110' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '110' },
        { label: this.$t('shop.fname2'), prop: 'fname', width: '120' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.fqty'), prop: 'fqty', align: 'right', width: '80' },
        { label: this.$t('market.busineState'), prop: 'fstatus', width: '80' },
        { label: this.$t('market.pickstatus'), type: 'states', prop: 'fpickstatus', width: '80' },
        { label: this.$t('market.workshop'), prop: 'fdept', width: '80' },
        { label: this.$t('market.hangUp'), prop: 'fispending', type: 'text4', width: '80' },
        { label: this.$t('market.hangUp1'), prop: 'zfispending', type: 'text2', width: '80' },
        { label: this.$t('market.closure'), type: 'text5', width: '80' },
        { label: this.$t('market.fmodel2'), prop: 'fmodel' },
        { label: this.$t('market.fulls'), type: 'text3', prop: 'fulls' },
        { label: this.$t('market.consignDate'), prop: 'fdeliverydate' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200' }
      ],
      orderBool: false,
      tableHeader1: [
        { label: this.$t('market.jcfprice'), prop: 'fprocesscost' },
        { label: this.$t('market.fsource'), prop: 'fsource' },
        { label: this.$t('market.userNo'), prop: 'fmobillno' },
        { label: this.$t('market.pushqty'), prop: 'fcompleteqty' },
        { label: this.$t('market.readyQty'), prop: 'freadyqty' },
        { label: this.$t('market.fcheckqty1'), prop: 'fcheckqty' },
        { label: this.$t('market.heqty'), prop: 'fhegeqty' },
        { label: this.$t('market.realWages1'), prop: 'real_wages' },
        { label: this.$t('market.realWagesprice'), prop: 'real_wagesprice' },
        { label: this.$t('market.fproqty'), prop: 'fproqty' },
        { label: this.$t('market.base_price'), prop: 'base_price' },
        { label: this.$t('market.creator'), prop: 'fcreator', width: '100' },
        { label: this.$t('market.createDate'), prop: 'fcreatedate', width: '100' }
      ],
      proData: []
    }
  },
  created() {
    this.searchSon = this.searchData
    this.handleGetUntreated(this.searchSon)
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    handleOrder(val) {
      if (val === this.$t('menu.qualityOrder')) {
        this.convert = this.$t('market.scbjy') // '生产订单至品质检验单'
        this.fbillTypeId = 184
        this.orderBool = true
        this.purpoorder1('SX_CHECKOUT')
      } else if (val === this.$t('menu.workFlowOrder')) {
        this.convert = this.$t('market.sczlc') // '生产订单至生产流程单'
        this.fbillTypeId = 245
        this.orderBool = true
        this.purpoorder1('SX_PROCESS')
      } else if (val === this.$t('menu.outProcessOrder')) {
        this.convert = this.$t('market.sczgx') // '生产订单至外包工序单'
        this.fbillTypeId = 1317
        this.orderBool = true
        this.purpoorder1('SX_OUTSOURCE')
      } else {
        this.orderBool = false
      }
    },
    // 品质检验订单单据
    async purpoorder1(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            return (toMxAmina(item), toPickStues(item))
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '生产订单列表')
        } else {
          queryMoList({
            pageSize: 5000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item), toPickStues(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '生产订单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取生产列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await queryMoList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.array.map(item => {
          return (toMxAmina(item), toPickStues(item))
        })
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList(ev) {
      this.searCollData = []
      this.currentPage = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 详情
    detailPurchase(ev) {
      const id = ev.fbillNo
      this.$router.push({ path: `/proOrderDetails/${id}` })
    },
    handleSelectAll(val) {
      this.val = val
      this.fbillno = val[0].fbillNo
      this.ppbombillno = val[0].ppbombillno
      this.selectVal = []
      this.fentryData = []
      this.fidsData = []
      val.forEach(res => {
        res.fbillNo && this.selectVal.push(res.fbillNo)
        this.fentryData.push(res.fentryId)
        this.fidsData.push(res.fid)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 公共函数
    toExamineFun(api, ev) {
      const DATA = {
        Numbers: this.selectVal,
        EntryIds: ev === 2 ? this.fentryData : []
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审批通过
    async audit(ev) {
      const api = ev === 1 ? auditPrdMos : unauditPrdMos
      this.toExamineFun(api)
    },
    // 提交、反提交
    async submit(ev) {
      const api = ev === 1 ? submitPrdMos : unsubmitPrdMos
      this.toExamineFun(api)
    },
    // 结案
    async closure(ev) {
      const api = ev === 1 ? endOrder : unEnd
      this.toExamineFun(api)
    },
    // 行结案
    async closeHang(ev) {
      const api = ev === 1 ? entryEnd : entryUnEnd
      this.toExamineFun(api, 2)
    },
    // 挂起、反挂起
    async hangUp(ev) {
      const DATA = {
        fids: this.fidsData,
        fispending: ev === 1 ? 1 : 0
      }
      updatefispending(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
      })
    },
    // 明细行挂起、反挂起
    async entryHangUp(ev) {
      const DATA = {
        fids: this.fentryData,
        fispending: ev === 1 ? 1 : 0
      }
      updateDetailedfispending(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
      })
    },
    // 删除
    delPublic() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delPrdMos
        this.toExamineFun(api)
      })
    },
    // 上查、下查
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 下推
    pushDown() {
      if (this.val && this.val.length <= 0) {
        this.$message.error('请选择数据!')
        return
      }
      this.isdanjuDialog = true
    },
    // 下推
    pushDownOrder() {
      const DATA = {
        SoucrceIds: this.fidsData,
        EntryIds: this.fentryData
      }
      if (this.orderLX === this.$t('menu.proStirageOrder')) {
        pushToPrdInstock(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/proStirageOrder/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proTuiStockDetail')) {
        pushToPrdUninstock(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/proTuiStockDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.qualityOrder')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        pushMoCheck(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/qualityDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.workFlowOrder')) { // 生产流程
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        insertProcess(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/workFlowDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.outProcessOrder')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        insertOutsource(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/outProcessDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proPickLian')) { // 领料
        const DATA = {
          SoucrceIds: this.fentryData
        }
        pushProToPicking(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/productionOrder/${res.data[0].fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proSupplTong')) { // 退料
        const DATA = {
          SoucrceIds: this.fentryData
        }
        pushProToReturnMater(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/proSuppleDetail/${res.data[0].fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.supplementary')) { // 补料
        const DATA = {
          SoucrceIds: this.fentryData
        }
        pushProToSupplement(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/supplementaryDetail/${res.data[0].fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
    },
    // 套打
    handleCom1(ev) {
      const id = this.selectVal.join(',')
      if (ev === 1) {
        this.$router.push({
          path: `/proGeneralOrd1/${id}`
        })
      } else {
        this.$router.push({
          path: `/proSuccessionOrd1/${id}`
        })
      }
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .el-dialog .el-dialog__body {
    padding: 0;
  }
  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
